<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.MaintenanceTableInfo2"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="150px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.PlanName"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          :label="dataList.PlanendDate"
          prop="endDate"
          :error="errorMsg.endDate"
        >
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="base-content-operate" style="float: left">
        <el-button type="primary" @click="onNew">{{ btn.Add2 }}</el-button>
        <el-button type="primary" @click="importData">{{
          btn.Import
        }}</el-button>
        <el-button type="primary" @click="bulkEdit">{{
          btn.BulkEdit
        }}</el-button>
        <el-button type="danger" @click="deleteData">{{
          btn.Delete
        }}</el-button>
        <el-input
          v-model="deviceNameNum"
          :placeholder="dataList.EnterDevice"
          style="width: 220px; margin-left: 20px"
        >
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <br />
      <div>
        <el-table
          ref="deviceMaintenanceInfoDtoList"
          :data="listData"
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column :label="dataList.DeviceNumber">
            <template slot-scope="scope">
              {{ scope.row.deviceNum }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          >
            <template slot-scope="scope">
              {{ scope.row.deviceName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceSpecifications">
            <template slot-scope="scope">
              {{ scope.row.specifications }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DevicePersonResponsibleId">
            <template slot-scope="scope">
              {{ scope.row.personResponsibleName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.Devicedepart">
            <template slot-scope="scope">
              {{ scope.row.departName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.MaintenanceTask">
            <template slot-scope="scope">
              {{ scope.row.project }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.ScheduledMaintenanceTime">
            <template slot-scope="scope">
              {{ formatTime(scope.row.planDate) }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.Week">
            <template slot-scope="scope">
              {{ scope.row.cycle + scope.row.unitName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.MaintenancePersonnel">
            <template slot-scope="scope">
              {{ scope.row.maintenancePersonName }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.Operation">
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.row)"
                  >{{ btn.Edit }}</el-link
                >
                &nbsp; &nbsp;
                <el-link
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index)"
                  >{{ btn.Delete }}</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button
          type="primary"
          style="width: 100px"
          @click="onSaveAndSubmit('formData')"
          >{{ btn.SaveAndSubmit }}</el-button
        >
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
    <DeviceMaintenanceProjectAddDialog
      v-if="deviceMaintenancePlanAddVisible"
      :dialog-form-visible.sync="deviceMaintenancePlanAddVisible"
      @closeDeviceMaintenanceProject="closeDeviceMaintenanceProject"
    />
    <DeviceMaintenanceProjectEditDialog
      v-if="deviceMaintenanceProjectEditVisible"
      :dialog-form-visible.sync="deviceMaintenanceProjectEditVisible"
      :row.sync="row"
      @closeDeviceMaintenanceProjectEdit="closeDeviceMaintenanceProjectEdit"
    />
    <ImportComponents
      ref="ImportComponents"
      v-model="importVisible"
      @success="closeDialog"
      @UploadMethod="UploadMethod"
      @DownloadMethod="DownloadMethod"
    />
  </div>
</template>

<script>
import {
  update,
  updateAndVerifyStart,
  get,
} from "../../../api/DeviceMaintenance.js";
import { DeviceImport } from "../../../api/Device.js";
import DeviceMaintenanceProjectAddDialog from "./DeviceMaintenanceProjectAddDialog.vue";
import DeviceMaintenanceProjectEditDialog from "./DeviceMaintenanceProjectEditDialog.vue";
import { DownloadMaintenancePlanTemplate } from "../../../api/DeviceImportComponents";
import { formatTime } from "../../../utils/time";
export default {
  name: "DeviceMaintenancePlanEditDialog",
  components: {
    DeviceMaintenanceProjectAddDialog,
    DeviceMaintenanceProjectEditDialog,
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      list: [],
      deviceMaintenancePlanAddVisible: false,
      deviceMaintenanceProjectEditVisible: false,
      deviceNameNum: "",
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      importVisible: false,
      initData: {
        id: 0,
        num: "",
        name: "",
        endDate: "",
        statusId: 0,
        statusName: "",
        assertDate: 0,
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      formData: {
        id: 0,
        num: "",
        name: "",
        endDate: "",
        statusId: 0,
        statusName: "",
        assertDate: 0,
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      editIndex: [],
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      formDataRules: {
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        endDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        statusId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        statusName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        assertDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        name: "",
        endDate: "",
        statusId: "",
        statusName: "",
        assertDate: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        name: "",
        endDate: "",
        statusId: "",
        statusName: "",
        assertDate: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
    };
  },
  computed: {
    listData() {
      return this.formData.deviceMaintenanceInfoDtoList.filter((record) => {
        return (
          record.deviceNum.includes(this.deviceNameNum) ||
          record.deviceName.includes(this.deviceNameNum)
        );
      });
    },
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {
    dialogFormVisible(val) {
      this.innerDialogFormVisible = val;
    },
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.get();
  },
  methods: {
    formatTime,
    // 上传
    UploadMethod(formData, fileCount) {
      formData.append("module", 1);
      DeviceImport(formData).then((res) => {
        if (res.code === 200) {
          var index = this.list.length;
          for (let i = 0; i < res.data.length; i++) {
            var row = {};
            row = res.data[i];
            row.index = index;
            this.formData.deviceMaintenanceInfoDtoList.push(
              JSON.parse(JSON.stringify(row))
            );
          }
          this.importVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 下载
    DownloadMethod: DownloadMaintenancePlanTemplate,
    closeDeviceMaintenanceProjectEdit(data) {
      // 判断是单独编辑还是批量编辑
      if (this.row.projectId) {
        // 单独编辑

        if (data.checked[0]) {
          this.row.project = data.project;
        }
        if (data.checked[1]) {
          this.row.planDate = data.planDate;
        }
        if (data.checked[2]) {
          this.row.cycle = data.cycle;
          this.row.unit = data.unit;
          this.row.unitName = data.unitName;
        }
        if (data.checked[3]) {
          this.row.maintenancePersonId = data.maintenancePersonId;
          this.row.maintenancePersonName = data.maintenancePersonName;
        }
      } else {
        // 批量编辑
        var rows = this.$refs.deviceMaintenanceInfoDtoList.selection;
        rows.map((item) => {
          if (data.checked[0]) {
            item.project = data.project;
          }
          if (data.checked[1]) {
            item.planDate = data.planDate;
          }
          if (data.checked[2]) {
            item.cycle = data.cycle;
            item.unit = data.unit;
            item.unitName = data.unitName;
          }
          if (data.checked[3]) {
            item.maintenancePersonId = data.maintenancePersonId;
            item.maintenancePersonName = data.maintenancePersonName;
          }
        });
      }
      this.row = {};
    },
    // 编辑
    handleEdit(row) {
      this.row = row;
      this.deviceMaintenanceProjectEditVisible = true;
    },

    handleDelete(index) {
      this.formData.deviceMaintenanceInfoDtoList.splice(index, 1);
    },
    closeDeviceMaintenanceProject(data) {
      var index = this.formData.deviceMaintenanceInfoDtoList.length;
      data.deviceList.map((device) => {
        data.projectList.map((project) => {
          var row = {};
          row = device;
          row.deviceNum = device.num;
          row.deviceName = device.name;
          row.index = index;
          row.project = project.project;
          row.planDate = project.planDate;
          row.cycle = project.cycle;
          row.unit = project.unit;
          row.unitName = project.unitName;
          row.maintenancePersonId = project.maintenancePersonId;
          row.maintenancePersonName = project.maintenancePersonName;
          row.deviceId = device.id;
          index++;
          this.formData.deviceMaintenanceInfoDtoList.push(
            JSON.parse(JSON.stringify(row))
          );
        });
      });
    },
    // 查询
    sel() {},
    // 删除
    deleteData() {
      // 获取被选中的行
      var rows = this.$refs.deviceMaintenanceInfoDtoList.selection;
      rows.map((row) => {
        var index = this.formData.deviceMaintenanceInfoDtoList.indexOf(row);
        this.formData.deviceMaintenanceInfoDtoList.splice(index, 1);
      });
    },
    // 批量编辑
    bulkEdit() {
      var rows = this.$refs.deviceMaintenanceInfoDtoList.selection;
      if (rows == null || rows.length <= 0) {
        this.$message.warningthis.$t("ModuleDevice.Device.PleaseSelectData");
      } else {
        this.row = {};
        this.deviceMaintenanceProjectEditVisible = true;
      }
    },
    // 导入
    importData() {
      this.importVisible = true;
    },
    // 新增选择设备
    onNew() {
      this.deviceMaintenancePlanAddVisible = true;
    },
    get() {
      get({ id: this.id })
        .then((res) => {
          this.formData = res.data;
        })
        .catch((res) => {});
    },
    cancel() {
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      if (
        this.formData.deviceMaintenanceInfoDtoList === null ||
        this.formData.deviceMaintenanceInfoDtoList.length === 0
      ) {
        this.$message.warning(
          this.$i18n.t("ModuleDevice.Message.TableDataNull")
        );
        return false;
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);

          var deviceIdList = [];
          this.formData.deviceMaintenanceInfoDtoList.map((obj) => {
            if (deviceIdList.indexOf(obj.deviceId) === -1) {
              deviceIdList.push(obj.deviceId);
            }
          });

          this.formData.deviceMaintenanceInfoCreateRequestList = [];
          deviceIdList.map((item) => {
            var deviceMaintenanceInfo = {};
            deviceMaintenanceInfo.deviceId = item;
            deviceMaintenanceInfo.DeviceMaintenanceProjectCreateRequestList =
              [];
            var projectList = this.formData.deviceMaintenanceInfoDtoList.filter(
              (item2) => {
                return item2.deviceId === item;
              }
            );
            deviceMaintenanceInfo.DeviceMaintenanceProjectCreateRequestList =
              projectList;
            this.formData.deviceMaintenanceInfoCreateRequestList.push(
              deviceMaintenanceInfo
            );
          });
          update(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    onSaveAndSubmit() {
      if (
        this.formData.deviceMaintenanceInfoDtoList == null ||
        this.formData.deviceMaintenanceInfoDtoList.length === 0
      ) {
        this.$message.warning(
          this.$i18n.t("ModuleDevice.Message.TableDataNull")
        );
        return false;
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          var deviceIdList = [];
          this.formData.deviceMaintenanceInfoDtoList.map((obj) => {
            if (deviceIdList.indexOf(obj.deviceId) === -1) {
              deviceIdList.push(obj.deviceId);
            }
          });

          this.formData.deviceMaintenanceInfoCreateRequestList = [];
          deviceIdList.map((item) => {
            var deviceMaintenanceInfo = {};
            deviceMaintenanceInfo.deviceId = item;
            deviceMaintenanceInfo.DeviceMaintenanceProjectCreateRequestList =
              [];
            var projectList = this.formData.deviceMaintenanceInfoDtoList.filter(
              (item2) => {
                return item2.deviceId === item;
              }
            );
            deviceMaintenanceInfo.DeviceMaintenanceProjectCreateRequestList =
              projectList;
            this.formData.deviceMaintenanceInfoCreateRequestList.push(
              deviceMaintenanceInfo
            );
          });
          updateAndVerifyStart(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("endDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("assertDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
